from arkid.spectacular_settings import SPECTACULAR_SETTINGS
from drf_spectacular.drainage import set_override, get_override
from drf_spectacular.utils import OpenApiExample
import functools
import inspect
from typing import Any, Dict, List, Optional, Type, Union

from rest_framework.fields import empty
from rest_framework.serializers import Serializer
from rest_framework.settings import api_settings

from drf_spectacular.drainage import error, get_view_methods, set_override, warn


def extend_schema_tags(name, description, page=None):
    tag = {
        'name': name,
        'description': description,
    }
    if page:
        tag['page'] = page
    SPECTACULAR_SETTINGS.get('TAGS').append(tag)


def extend_schema(
        operation_id=None,
        parameters=None,
        request=empty,
        responses=empty,
        auth=None,
        description=None,
        summary=None,
        deprecated=None,
        tags=None,
        exclude=False,
        operation=None,
        methods=None,
        versions=None,
        examples: Optional[List[OpenApiExample]] = None,
        action=None,
        roles=[],
        action_type=None
):
    """
    decorator mainly for the "view" method kind. partially or completely overrides
    what would be generated by drf-spectacular.

    :param operation_id: replaces the auto-generated operation_id. make sure there
        are no naming collisions.
    :param parameters: list of additional or replacement parameters added to the
        auto-discovered fields.
    :param responses: replaces the discovered Serializer. Takes a variety of
        inputs that can be used individually or combined

        - ``Serializer`` class
        - ``Serializer`` instance (e.g. ``Serializer(many=True)`` for listings)
        - ``dict`` with status codes as keys and `Serializers` as values.
        - ``dict`` with tuple (status_code, media_type) as keys and `Serializers` as values.
        - :class:`.PolymorphicProxySerializer` for signaling that
          the operation may yield data from different serializers depending
          on the circumstances.
    :param request: replaces the discovered ``Serializer``.
    :param auth:
    :param description: replaces discovered doc strings
    :param summary: an optional short summary of the description
    :param deprecated: mark operation as deprecated
    :param tags: override default list of tags
    :param exclude: set True to exclude operation from schema
    :param operation: manually override what auto-discovery would generate. you must
        provide a OpenAPI3-compliant dictionary that gets directly translated to YAML.
    :param methods: scope extend_schema to specific methods. matches all by default.
    :param versions: scope extend_schema to specific API version. matches all by default.
    :param examples: attach request/response examples to the operation
    :return:
    """
    def decorator(f):
        BaseSchema = (
            # explicit manually set schema or previous view annotation
            getattr(f, 'schema', None)
            # previously set schema with @extend_schema on views methods
            or getattr(f, 'kwargs', {}).get('schema', None)
            # previously set schema with @extend_schema on @api_view
            or getattr(getattr(f, 'cls', None), 'kwargs', {}).get('schema', None)
            # the default
            or api_settings.DEFAULT_SCHEMA_CLASS
        )

        if not inspect.isclass(BaseSchema):
            BaseSchema = BaseSchema.__class__

        def is_in_scope(ext_schema):
            version, _ = ext_schema.view.determine_version(
                ext_schema.view.request,
                **ext_schema.view.kwargs
            )
            version_scope = versions is None or version in versions
            method_scope = methods is None or ext_schema.method in methods
            return method_scope and version_scope

        class ExtendedSchema(BaseSchema):
            def get_operation(self, path, path_regex, method, registry):
                self.method = method

                if exclude and is_in_scope(self):
                    return None
                if operation is not None and is_in_scope(self):
                    return operation
                return super().get_operation(path, path_regex, method, registry)

            def get_operation_id(self):
                if operation_id and is_in_scope(self):
                    return operation_id
                return super().get_operation_id()

            def get_override_parameters(self):
                if parameters and is_in_scope(self):
                    return super().get_override_parameters() + parameters
                return super().get_override_parameters()

            def get_auth(self):
                if auth and is_in_scope(self):
                    return auth
                return super().get_auth()

            def get_examples(self):
                if examples and is_in_scope(self):
                    return examples
                return super().get_examples()

            def get_request_serializer(self):
                if request is not empty and is_in_scope(self):
                    return request
                return super().get_request_serializer()

            def get_response_serializers(self):
                if responses is not empty and is_in_scope(self):
                    return responses
                return super().get_response_serializers()

            def get_description(self):
                if description and is_in_scope(self):
                    return description
                return super().get_description()

            def get_summary(self):
                if summary and is_in_scope(self):
                    return str(summary)
                return super().get_summary()

            def is_deprecated(self):
                if deprecated and is_in_scope(self):
                    return deprecated
                return super().is_deprecated()

            def get_tags(self):
                if tags is not None and is_in_scope(self):
                    return tags
                return super().get_tags()

            def get_action(self):
                if action and is_in_scope(self):
                    return action
                return super().get_action()

            def get_action_type(self):
                if action_type and is_in_scope(self):
                    return action_type
                return ''

            def get_roles(self):
                if roles and is_in_scope(self):
                    return roles
                return []

        if inspect.isclass(f):
            # either direct decoration of views, or unpacked @api_view from OpenApiViewExtension
            if operation_id is not None or operation is not None:
                error(
                    f'using @extend_schema on viewset class {f.__name__} with parameters '
                    f'operation_id or operation will most likely result in a broken schema.'
                )
            # reorder schema class MRO so that view method annotation takes precedence
            # over view class annotation. only relevant if there is a method annotation
            for view_method in get_view_methods(view=f, schema=BaseSchema):
                if 'schema' in getattr(view_method, 'kwargs', {}):
                    view_method.kwargs['schema'] = type(
                        'ExtendedMetaSchema', (view_method.kwargs['schema'], ExtendedSchema), {}
                    )
            # persist schema on class to provide annotation to derived view methods.
            # the second purpose is to serve as base for view multi-annotation
            f.schema = ExtendedSchema()
            return f
        elif callable(f) and hasattr(f, 'cls'):
            # 'cls' attr signals that as_view() was called, which only applies to @api_view.
            # keep a "unused" schema reference at root level for multi annotation convenience.
            setattr(f.cls, 'kwargs', {'schema': ExtendedSchema})
            # set schema on method kwargs context to emulate regular view behaviour.
            for method in f.cls.http_method_names:
                setattr(getattr(f.cls, method), 'kwargs', {'schema': ExtendedSchema})
            return f
        elif callable(f):
            # custom actions have kwargs in their context, others don't. create it so our create_view
            # implementation can overwrite the default schema
            if not hasattr(f, 'kwargs'):
                f.kwargs = {}
            # this simulates what @action is actually doing. somewhere along the line in this process
            # the schema is picked up from kwargs and used. it's involved my dear friends.
            # use class instead of instance due to descriptor weakref reverse collisions
            f.kwargs['schema'] = ExtendedSchema
            return f
        else:
            return f

    return decorator
